<template>
	<view class="content">
		<view class="top-area">
			<view class="top-tilte">
				<text>{{topTile}}</text>
				<text class="green">({{$t('inspection.offline.offline')}})</text>
			</view>
			<view class="top-btns">
				<view class="btn-item" @click="goDanger">
					<image class="img" src="../../../../static/images/icon/min2.png" /> {{$t('inspection.area.hazard')}}
				</view>
				<view class="btn-item" @click="showBeforeInspect">
					<image class="img" src="../../../../static/images/icon/min1.png" /> {{$t('inspection.taskPlan.inspPreparation')}}
				</view>
				<view class="btn-item" @click="goSummanry">
					<image class="img" src="../../../../static/images/icon/min4.png" /> {{$t('inspection.taskPlan.finishReport')}}
				</view>
			</view>
		</view>

		<scroll-view scroll-y :class="isEdit ? 'scrollList' : 'commonList'">
			<template v-for="(item, index) in listData">
				<view class="list-item" @click="toInfo(item, index)" :key="index">
					<view class="item-row">
						<view class="row-data" v-if="isAreaLocation == 1">
							<text class='title'>{{$t('inspection.area.areaNo')}}：</text>
							<text class="desc">{{item.areaNo}}</text>
						</view>
						<view class="row-data" v-if="isAreaLocation == 0">
							<text class='title'>{{$t('equipment.common.devCode')}}：</text>
							<text class="desc">{{item.locaNo}}</text>
						</view>
						<view class="row-data">
							<text class="red" v-if="item.areaExecStatus == '0'">{{$t('inspection.taskExecute.unchecked')}}</text>
							<text class="orange" v-if="item.areaExecStatus == '1'">{{$t('inspection.taskExecute.partialInspection')}}</text>
							<text class="green" v-if="item.areaExecStatus == '2'">{{$t('inspection.taskExecute.allInspection')}}</text>
							<image class="img" src="../../../../static/images/icon/min5.png" mode=""></image>
						</view>
					</view>
					<view class="item-row" v-if="isAreaLocation == 1">
						<view class="row-data">
							<text class='title'>{{$t('inspection.area.areaName')}}：</text>
							<text class="desc">{{item.areaName}} </text>
						</view>
					</view>
					<view class="item-row" v-if="isAreaLocation == 0">
						<view class="row-data">
							<text class='title'>{{$t('equipment.common.devName')}}：</text>
							<text class="desc">{{item.locaName}} </text>
						</view>
					</view>
				</view>
			</template>
		</scroll-view>
		
		<view class="bottomBtn" v-if="showBtn">
			<button type="primary" @click="handleBtn">{{ btnText }}</button>
		</view>
		
		<upload :taskId="taskId"></upload>
	</view>
</template>

<script>
	import upload from './components/upload.vue'
	import * as sqliteUtil from '@/utils/sqlite.js'
	import * as sqliteInspect from '@/utils/business/inspectSqlite.js'
	import { utilities } from '@/utils/common.js'
	import { inspect as util } from '@/utils/business/common.js'
	import NFCMixin from '@/utils/business/businessNFC.js'

	export default {
		mixins: [
			NFCMixin
		],
		components: {
			upload
		},
		data() {
			return {
				listData: [],
				taskId: '',
				topTile: '',
				lineId: '',
				isAreaLocation: 1,
				isScanHand: '',
				preparing: '',
				showBtn: false,
				isEdit: true,
				btnText: '',
				btnType: '',
				networkStatus: 'offline',
				nfcData: '',
				pattern: {
					color: '#7A7E83',
					backgroundColor: '#fff',
					selectedColor: '#007AFF',
					buttonColor: '#007AFF',
					iconColor: '#fff'
				},
				content: [{
					iconPath: '/static/images/icon/transfer.png',
					text: '上传',
					active: true
				}]
			}
		},
		watch: {
			nfcData: {
				handler(val) {
					this.handleNfc()
				}
				// immediate: true
			}
		},
		onLoad(option) {
			this.taskId = option.taskId
			
			// #ifdef APP-PLUS
			this.listenNFCStatus()
			this.readyRead = true
			// #endif
		},
		onShow() {
			this.listData = [];
			this.loadData();
		},
		onUnload() {
			this.readyRead = false
			uni.removeStorageSync("nfcData")
		},
		methods: {
			async loadData() {
				uni.showLoading({
					title: this.$t('common.loading')
				})
				
				await sqliteUtil.selectTableInfo('m_ri_task', 'task_id', this.taskId).then(res=>{
					// 下划线转驼峰
					utilities.formatHumpLineTransfer(res)
					
					this.topTile = res[0].taskName
					this.lineId = res[0].lineId
					this.preparing = res[0].preparing
					this.isAreaLocation = res[0].isAreaLocation
					this.isScanHand = res[0].isScanHand
					this.isEdit = res[0].taskState === 3 ? false : true
					
					if(this.isEdit) {
						// 扫码
						if(this.isScanHand === 0) {
							this.showBtn = true
							this.btnText = this.$t('inspection.taskExecute.scanOrNfc')
							this.btnType = "QR"
						} 
						// 手工选择
						else if(this.isScanHand === 1) {
							this.showBtn = true
							this.btnText = this.$t('inspection.taskExecute.scanOrNfc')
							this.btnType = "QR"
						}
						// 物联设备
						else if(this.isScanHand === 2) {
							this.showBtn = true
							this.btnText = this.$t('inspection.taskExecute.nfcRead')
							this.btnType = "NFC"
						}
					}
				})
				
				// this.getPreparingFun()
				
				sqliteInspect.taskPageTypeList(this.isAreaLocation, this.taskId).then(res => {
					uni.hideLoading()
					
					if (res && res.length > 0) {
						// 下划线转驼峰
						utilities.formatHumpLineTransfer(res)
						
						this.listData = res
						// 状态赋值
						this.handleExecStatus()
					}
				})
			},
			handleExecStatus() {
				let that = this
				that.listData.forEach(async function(item, index, arr){
					let condition = [
						{ key: "task_id", value: that.taskId },
					]
					if(that.isAreaLocation == "0") {
						let param = {
							key: "loca_id",
							value: item.locaId
						}
						condition.push(param)
					} else if(that.isAreaLocation == "1") {
						let param = {
							key: "area_id",
							value: item.areaId
						}
						condition.push(param)
					}
					//获得任务和区域下所有检查项数量
					let allList = await sqliteUtil.selectTableInfoMore('m_ri_task_inspection', condition)
					let allCount = allList.length
					
					//获得任务和区域下未检检查项数量
					let notList = allList.filter(r => r.exec_status == '0')
					let notCount = notList.length
					
					// 区域巡检状态(0-待检，1检查中，2已检)
					if(notCount == 0) { // 说明：未检数量为0，说明状态全部为已检或免检，所以是区域状态是已检
						item.areaExecStatus = 2
					} else {
						if(notCount < allCount) { // 说明：未检数量小于总数量且大于0，说明部分为已检或免检，所以是区域状态是检查中
							item.areaExecStatus = 1
						} else { // 说明：未检数量等于总数量，说明状态全部为未检，所以是区域状态是未检
							item.areaExecStatus = 0
						}
					}
					arr.splice(index, 1, item)
				})
			},
			getPreparingFun() {
				if (this.isEdit && this.preparing) {
					this.showBeforeInspect();
				}
			},
			showBeforeInspect() {
				uni.showModal({
					title: this.$t('inspection.taskPlan.inspPreparation'),
					content: this.preparing,
					showCancel: false,
					confirmText: this.$t('inspection.taskExecute.understood'),
					confirmColor: '#007aff',
					success: function(res) {
						if (res.confirm) {
							console.log('用户点击确定');
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			goSummanry() {
				uni.navigateTo({
					url: "/pages/business/inspect/offline/summary?taskId=" + this.taskId + '&topTile=' + this.topTile + '&isEdit=' + this.isEdit
				})
			},
			goDanger() {
				uni.navigateTo({
					url: "/pages/business/inspect/offline/danger?lineId=" + this.lineId
				})
			},
			toInfo(item, index) {
				this.listData = this.listData.filter((item2, index2) => {
					if (index == index2) {
						item2.active = true
					} else {
						item2.active = false
					}
					return item2
				})
				
				let url = "/pages/business/inspect/offline/inspectItem?taskId=" + this.taskId + "&lineId=" + this.lineId +
					"&areaId=" + item.areaId + "&locaId=" + item.locaId + "&isAreaLocation=" + this.isAreaLocation
				
				if(this.isScanHand === 0 || this.isScanHand === 2 || !this.isEdit) {
					url += '&isEdit=ok'
				}
				
				uni.navigateTo({
					url: url
				})
				
				let data = ""
				if(this.isAreaLocation === 1) {
					data = "TYPE=IDPOS&ID=" + item.areaId +"&NO=" + item.areaNo
				} else if(this.isAreaLocation === 0){
					data = "TYPE=IDPOS&ID=" + item.locaId +"&NO=" + item.locaNo
				}
				uni.setStorageSync("nfcData", data)
			},
			handleBtn() {
				if(this.btnType == "QR") {
					uni.navigateTo({
						url: "/pages/business/inspect/offline/scanCode?taskId=" + this.taskId + "&lineId=" + this.lineId + "&isAreaLocation=" + this.isAreaLocation
						// url: "/pages/business/inspect/offline/sureCode?taskId=" + this.taskId + "&lineId=" + this.lineId + "&isAreaLocation=" + this.isAreaLocation
					})
				} else if(this.btnType == "NFC") {
					this.nfcData = null
					// NFC读取数据
					this.readData()
				}
			},
			async handleNfc() {
				if(this.nfcData) {
					let that = this
					// 获取当前页面
					let pages = getCurrentPages();
					let page = pages[pages.length - 1];
					// 由于NFC功能是mixins，防止watch在其他页面执行，此处限制页面路由
					if(page.route.indexOf('/inspectDetail') !== -1 || page.route.indexOf('/inspectItem') !== -1) {
						let isCurrent = true
						if(page.route.indexOf('/inspectDetail') === -1) {
							isCurrent = false
						}
						
						// 验证
						let result = await util.verifyControlMode(that.taskId, that.nfcData, 'scan', that.networkStatus)
						if(result.isPass) {
							let url = './inspectItem?taskId=' + that.taskId + '&lineId=' + that.lineId + 
								'&areaId=' + result.areaId + '&locaId=' + result.locaId + '&isAreaLocation=' + that.isAreaLocation
							
							if(!isCurrent) {
								let prevNfc = uni.getStorageSync("nfcData")
								// 过滤掉NAME字段
								let nowNfc = that.nfcData.substring(1, that.nfcData.indexOf('&NAME'))
								if(prevNfc && nowNfc != prevNfc) {
									let content = ''
									if(that.isAreaLocation === 1) {
										content = '区域不一致，请确认是否切换'
									} else if(that.isAreaLocation === 0) {
										content = '设备不一致，请确认是否切换'
									}
									uni.showModal({
										title: that.$t('baseCommon.message.tips'),
										content: content,
										success: function (res) {
											if (res.confirm) {
												uni.redirectTo({
													url: url 
												});
												uni.setStorageSync("nfcData", that.nfcData)
											} else if (res.cancel) {
												that.nfcData = ''
											}
										}
									})
								} else {
									uni.redirectTo({
										url: url 
									});
									uni.setStorageSync("nfcData", that.nfcData)
								}
							} else {
								uni.navigateTo({
									url: url
								});
								uni.setStorageSync("nfcData", that.nfcData)
							}
						} else {
							uni.showModal({
								title: that.$t('baseCommon.message.tips'),
								content: result.msg,
								success: function (res) {
									if (res.confirm) {
										if(!isCurrent) {
											page.$vm.pageBack()
											uni.removeStorageSync("nfcData")
										} else {
											that.nfcData = ''
										}
									} else if (res.cancel) {
										that.nfcData = ''
									}
								}
							})
						}
					}
				}
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #F1F1F1;
	}
	
	.top-area {
		background: white;
	
		.top-tilte {
			padding: 12px 0;
			margin: 0 10px;
			color: #333;
			text-align: left;
			border-bottom: 1rpx solid #eee;
		}
	
		.top-btns {
			height: 45px;
			margin: 0 10px;
			border-bottom: 1rpx solid #eee;
			display: flex;
			align-items: center;
	
			.btn-item {
				font-size: 12px;
				color: #666;
				display: flex;
				align-items: center;
				justify-content: center;
				width: 33%;
				border-right: 1rpx solid #eee;
	
				.img {
					margin-right: 5px;
					width: 16px;
					height: 16px;
				}
			}
	
			.btn-item:last-child {
				border-right: none;
			}
		}
	}
	
	.scrollList {
		background-color: #fff;
		/* #ifdef APP-PLUS */
		height: calc(100vh - 175px);
		/* #endif*/
		/* #ifdef H5 */
		height: calc(100vh - 215px);
		/* #endif*/
	}
	
	.commonList {
		background-color: #fff;
	}
	
	.list-item {
		width: 100%;
		padding: 15px 10px;
		padding-bottom: 0;
		font-size: 14px;
		color: #333;
		border-bottom: 1rpx solid #eee;
		box-sizing: border-box;
	
		.item-row {
			display: flex;
			align-items: center;
			justify-content: space-between;
	
			.row-data {
				display: flex;
				align-items: center;
				margin-bottom: 15px;
				
				.img {
					width: 12px;
					height: 12px;
					margin-left: 3px;
				}
				
				.title {
					color: #999;
				}
	
				.desc {
					color: #333;
					margin-left: 10px;
				}
			}
		}
	}

	.green {
		color: $uni-color-success;
	}

	.red {
		color: $uni-color-error;
	}
	
	.orange {
		color: $uni-color-warning;
	}
	
	.bottomBtn {
		position: fixed;
		bottom: 8px;
		width: 96%;
		left: 2%;
	
		button {
			background-color: #1E91E6;
		}
	}
</style>